package main

import (
	"bufio"
	"fmt"
	"io"
	"manygo/mytools"
	"os"
	"strings"
	// "sync"

	"github.com/360EntSecGroup-Skylar/excelize"

	"path/filepath"
)

func i2n(i int) string {
	ss := ""
	mlist := [26]string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
	if i < 27 {
		ss = mlist[i-1]

	} else {

		c := i / 26
		c2 := i % 26
		// fmt.Println(c, c2)
		if c2 == 0 {
			c2 = 26
			c--
		}
		if c < 27 {
			ss += mlist[c-1]
			ss += mlist[c2-1]
		}
	}
	return ss
}

// func split(s string) {
// 	s1 := strings.Split(s, ",")

// }

//processLine 13
// func processLine(line []byte) {
// 	os.Stdout.Write(line)
// }

//ReadLine 13
func ReadLine(filePth, v string) error {
	f, err := os.Open(filePth)
	if err != nil {
		return err
	}
	defer f.Close()
	lll := 500000
	rr := 0

	bfRd := bufio.NewReader(f)
	n := 2
	num := 1
	xlsx := excelize.NewFile()
	aa := "账单编号,雇员编号,公司编号,所属月,雇员姓名,付款类型,账单公司编号,委托机构,城市,核销状态,核销时间,金额1,金额2,金额3,金额4,金额5,金额6,金额7,金额8,金额9,金额10,金额11,金额12,金额13,金额14,金额15,金额16,金额17,金额18,金额19,金额20,金额21,金额22,金额23,金额24,金额25"
	s1 := strings.Split(aa, ",")
	for ind, v := range s1 {
		xlsx.SetCellValue("Sheet1", i2n(ind+1)+"1", v)
	}

	// var wg sync.WaitGroup
	// wg.Add(1)
	for {
		rr++

		line, err := bfRd.ReadBytes('\n')
		s1 = strings.Split(string(line), ",")
		for ind, v := range s1 {
			dd := i2n(ind+1) + mytools.Int2String(n)
			// fmt.Println(dd)
			xlsx.SetCellValue("Sheet1", dd, v)
		}

		n++
		if n > 100001 {
			n = 2

			err = xlsx.SaveAs(`d:\mm1` + v + mytools.Int2String(num) + `.xlsx`)
			if err != nil {
				fmt.Println(err)
			}
			num++
			xlsx = excelize.NewFile()
			for ind, v := range s1 {
				xlsx.SetCellValue("Sheet1", i2n(ind+1)+"1", v)
			}

		}

		// hookfn(line)    //放在错误处理前面，即使发生错误，也会处理已经读取到的数据。

		if err != nil { //遇到任何错误立即返回，并忽略 EOF 错误信息
			if err == io.EOF {
				return nil
			}
			return err
		}
		if rr%5000 == 0 {
			fmt.Println(rr*100/lll, "%")
		}

	}
	return nil
}

func main() {
	path, err := os.Executable()
	if err != nil {
		panic(err)
	}
	dir := filepath.Dir(path)
	v := mytools.MyInput("运行的txt文件名称")

	fmt.Println(ReadLine(filepath.Join(dir, v)+`.txt`, v))

}
